package com.estore.src.com.estore02.service;

import com.estore.src.com.estore02.model.Product;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 商品服务类，负责商品相关的业务逻辑
 */
public class ProductService {

    private final Map<String, Product> productData = new HashMap<>();
    private String dataFilePath;
    private String backupFilePath;

    /**
     * 构造函数，初始化配置和数据
     */
    public ProductService() {
        // 加载配置
        loadConfig();
        // 加载数据
        loadData();

        // 如果数据文件不存在，初始化默认数据
        if (productData.isEmpty()) {
            initializeDefaultProducts();
        }
    }

    /**
     * 加载配置文件
     */
    private void loadConfig() {
        Properties props = new Properties();
        try (InputStreamReader reader = new InputStreamReader(
                new FileInputStream("config.properties"), "UTF-8")) {
            props.load(reader);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
            backupFilePath = props.getProperty("backup.file.path", "products.dat.bak");
            System.out.println("✅ 配置文件加载成功");
            System.out.println("📁 数据文件路径: " + dataFilePath);
            System.out.println("📁 备份文件路径: " + backupFilePath);
        } catch (FileNotFoundException e) {
            System.out.println("⚠️  配置文件不存在，使用默认配置");
            dataFilePath = "products.dat";
            backupFilePath = "products.dat.bak";
        } catch (IOException e) {
            System.out.println("❌ 配置文件读取失败: " + e.getMessage());
            dataFilePath = "products.dat";
            backupFilePath = "products.dat.bak";
        }
    }

    /**
     * 保存数据到文件
     */
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(dataFilePath))) {
            oos.writeObject(productData);
            System.out.println("✅ 商品数据已保存到: " + dataFilePath);
        } catch (IOException e) {
            System.out.println("❌ 数据保存失败: " + e.getMessage());
        }
    }

    /**
     * 从文件加载数据
     */
    @SuppressWarnings("unchecked")
    private void loadData() {
        File dataFile = new File(dataFilePath);
        if (!dataFile.exists()) {
            System.out.println("⚠️  数据文件不存在，将创建新文件");
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(dataFilePath))) {
            Map<String, Product> loadedData = (Map<String, Product>) ois.readObject();
            productData.clear();
            productData.putAll(loadedData);
            System.out.println("✅ 商品数据加载成功，共 " + productData.size() + " 个商品");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("❌ 数据加载失败: " + e.getMessage());
            System.out.println("⚠️  将使用默认商品数据");
        }
    }

    /**
     * 备份数据文件
     */
    public void backupData() {
        File sourceFile = new File(dataFilePath);
        if (!sourceFile.exists()) {
            System.out.println("❌ 源数据文件不存在，无法备份");
            return;
        }

        try (FileInputStream fis = new FileInputStream(dataFilePath);
             FileOutputStream fos = new FileOutputStream(backupFilePath)) {

            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

            System.out.println("✅ 数据备份成功: " + backupFilePath);
            System.out.println("📊 备份文件大小: " + new File(backupFilePath).length() + " 字节");

        } catch (IOException e) {
            System.out.println("❌ 数据备份失败: " + e.getMessage());
        }
    }

    /**
     * 初始化默认商品数据（仅当数据文件不存在时使用）
     */
    private void initializeDefaultProducts() {
        productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100));
        productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));
        productData.put("p003", new Product("p003", "颈椎康复指南", 45.0, 200));
        productData.put("p004", new Product("p004", "生发秘籍", 88.0, 0));
        productData.put("p005", new Product("p005", "Python编程", 79.0, 80));
        productData.put("p006", new Product("p006", "数据结构与算法", 120.0, 30));
        System.out.println("✅ 默认商品数据初始化完成");

        // 保存初始数据
        saveData();
    }

    /**
     * 获取所有商品列表
     */
    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    /**
     * 根据ID查找商品
     */
    public Product findProductById(String id) {
        return productData.get(id);
    }

    /**
     * 验证商品是否存在
     */
    public boolean isProductExist(String id) {
        return productData.containsKey(id);
    }

    /**
     * 验证库存是否充足
     */
    public boolean isStockSufficient(String id, int quantity) {
        Product product = productData.get(id);
        return product != null && product.getStock() >= quantity;
    }

    /**
     * 减少商品库存
     */
    public void reduceStock(String id, int quantity) {
        Product product = productData.get(id);
        if (product != null) {
            product.setStock(product.getStock() - quantity);
            // 库存变化后自动保存
            saveData();
        }
    }

    /**
     * 获取商品总数
     */
    public int getTotalProductCount() {
        return productData.size();
    }

    /**
     * 获取有库存的商品列表
     */
    public List<Product> getAvailableProducts() {
        List<Product> availableProducts = new ArrayList<>();
        for (Product product : productData.values()) {
            if (product.getStock() > 0) {
                availableProducts.add(product);
            }
        }
        return availableProducts;
    }
}